package cn.edu.lcu.cs.designpattern.composite.transparency;

import java.util.ArrayList;
import java.util.List;

public class Branch extends Node {
    private List<Node> children = new ArrayList<>();

    public Branch(String value) {
        setType(NODE_TYPE_BRANCH);
        setValue(value);
    }

    @Override
    public List<Node> getChildren() {
        return children;
    }

    public Branch() {
        setType(NODE_TYPE_BRANCH);
    }

    @Override
    public void add(Node child) {
        child.setParent(this);
        this.children.add(child);
    }

    @Override
    public void remove(Node child) {
        this.children.remove(child);
    }

    /**
     * 根据索引获取孩子节点
     *
     * @param index 孩子节点的索引，起始于0
     * @return
     */
    @Override
    public Node getChild(int index) {
        if (index >= 0 && index < this.children.size()) {
            return this.children.get(index);
        } else {
            return null;
        }
    }

    @Override
    public void print() {
        System.out.println("分枝结点【" + getValue() + "】");
    }


    /**
     * 深度优先遍历分枝
     *
     * @param node
     */
    @Override
    public void traversal(Node node) {
        node.print();
        for (Node item : node.getChildren()) {
            traversal(item);
        }
    }
}
